//
//  JokesViewController.m
//  KL
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//
#define KLTipLabelW 200
#define KLTipLabelH 40
#define KLFeedBackLabelW 170
#define KLFeedBackLabelH 50
#define KLFirstPage 1

#import "JokesViewController.h"
#import "MahuaViewController.h"
#import "Mahua.h"
#import "MahuaCell.h"
#import <SVProgressHUD.h>
#import "UMSocial.h"

@interface JokesViewController () <MahuaCellDelegate, UMSocialUIDelegate>
@property (nonatomic, strong) NSMutableArray *jokes;
/** 提示框 */
@property (nonatomic, weak) UILabel *tipLabel;
/** 返回提示框 */
@property (nonatomic, weak) UILabel *feedBack;
/** 显示数据的页数 */
@property (nonatomic, assign) NSInteger page;
/** 判断提示框label动画是否正在进行 */
@property (nonatomic, assign, getter=isTipLabel) BOOL tiPLabel;
/** 判断反馈label动画是否正在进行 */
@property (nonatomic, assign, getter=isFeedBackLabel) BOOL feedBackLabel;

@end

@implementation JokesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 自动刷新控件
    [self setUpRefresh];
    
    // 自动计算行高
    self.tableView.estimatedRowHeight = 40;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    // 给页数一个初始值
    self.page = 1;
    
    // 设置footerview
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
    
    // 添加监听通知
    [KLNotificationCenter addObserver:self selector:@selector(getNewData) name:@"getNewData" object:nil];
}

#pragma mark - 通知的调用方法
- (void)getNewData {
    [self.tableView.mj_header beginRefreshing];
}

// 需求,在左右滑动的时候请求不同url的数据,但是如果不下拉就不刷新,下拉才刷新
#pragma mark - 重写setter方法,再次发送请求
- (void)setUrlString:(NSString *)urlString {
    _urlString = urlString;
    [self setUpRefresh];
    
    self.jokes = (NSMutableArray *)[Mahua mahuasWith:self.index];
    
    
    // 自动进入刷新状态,需要在集成好刷新控件之后才可以使用
    if (self.jokes.count == 0) {
        [self.tableView.mj_header beginRefreshing];
    }
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [self.jokes removeAllObjects];
}

#pragma mark - 集成刷新控件
- (void)setUpRefresh {
    __unsafe_unretained UITableView *tableView = self.tableView;
    __weak typeof(self) weakSelf = self;
    // 下拉刷新
    tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 请求网络数据
        [Mahua mahuaWithUrlString:self.urlString index:self.index page:KLFirstPage finishedBlock:^(NSArray *arrayData) {
#warning 需要判断是否请求到了数据,如果没有数据,那么需要提示用户
            // 判断是否有数据
            if (arrayData.count) {
                weakSelf.jokes = (NSMutableArray *)arrayData;
                // 刷新数据
                [tableView reloadData];
                
                // 提示框
                [self showTipLabel];
                
                // 通知mahua控制器显示channellabel
                [KLNotificationCenter postNotificationName:@"didLoadData" object:nil];
            }else { // 没有加载到数据,网路不好
                [SVProgressHUD showErrorWithStatus:@"网络信号不好..."];
            }
            // 结束刷新
            [tableView.mj_header endRefreshing];
        }];

    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 每次请求数据的时候在原来的基础上+1
        [Mahua mahuaWithUrlString:self.urlString index:self.index page:++self.page finishedBlock:^(NSArray *arrayData) {
            
            // 判断是否有数据
            if (arrayData.count) {
                // 把数据插入到原来数组的最后
                [weakSelf.jokes addObjectsFromArray:arrayData];
                // 刷新数据
                [tableView reloadData];
            }else { // 没有加载到数据,网路不好
                [SVProgressHUD showErrorWithStatus:@"网络信号不好..."];
            }
        }];
            // 结束刷新
            [tableView.mj_footer endRefreshing];

    }];
    
    
}

#pragma mark - 提示框
- (void)showTipLabel {
    if (self.isTipLabel) return;
    // 核心动画
    CABasicAnimation *anim = [CABasicAnimation animation];
    anim.keyPath = @"transform.scale";
    anim.toValue = [NSNumber numberWithFloat:1.1];
    [self.tipLabel.layer addAnimation:anim forKey:nil];
    
    [UIView animateWithDuration:0.1 animations:^{
        self.tipLabel.alpha = 1.0;
        self.tiPLabel = YES;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 delay:1.5 options:0 animations:^{
            self.tipLabel.alpha = 0.0;
        } completion:^(BOOL finished) {
            self.tiPLabel = NO;
            [self.tipLabel removeFromSuperview];
        }];
    }];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.jokes.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取出模型
    Mahua *mahua = self.jokes[indexPath.row];
    static NSString *ID = nil;
    
    if ([mahua.format isEqualToString:@"word"]) {
        ID = @"word_cell";
    }else if ([mahua.format isEqualToString:@"image"]) {
        ID = @"image_cell";
    }
    
    MahuaCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.delegate = self;
    cell.mahua = mahua;
    
    return cell;
}

- (void)dealloc {
    [KLNotificationCenter removeObserver:self];
}

#pragma mark - scrollviewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [KLNotificationCenter postNotificationName:@"beginDragging" object:nil];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [KLNotificationCenter postNotificationName:@"endDragging" object:nil];
}

#pragma mark - MahuaCellDelegate
- (void)mahuaCellDidClickUnlikeButton:(MahuaCell *)mahuaCell {
    if (self.isFeedBackLabel) return;
    // 核心动画
    CABasicAnimation *anim = [CABasicAnimation animation];
    anim.keyPath = @"transform.scale";
    anim.toValue = [NSNumber numberWithFloat:1.1];
    [self.feedBack.layer addAnimation:anim forKey:nil];
    
    [UIView animateWithDuration:0.1 animations:^{
        self.feedBackLabel = YES;
        self.feedBack.alpha = 1.0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 delay:1.5 options:0 animations:^{
            self.feedBack.alpha = 0.0;
        } completion:^(BOOL finished) {
            self.feedBackLabel = NO;
            [self.feedBack removeFromSuperview];
        }];
    }];
}

#pragma mark - 通知mainviewcontroller显示分享页面
- (void)mahuaCellDidClickShareButton:(MahuaCell *)mahuaCell {
    // 取出cell所在的indexpath
    NSIndexPath *indexPath = [self.tableView indexPathForCell:mahuaCell];
//    KLLog(@"%ld", indexPath.row);
    [KLNotificationCenter postNotificationName:@"didShareButton" object:mahuaCell];
    // 隐藏没有安装的应用
//    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline]];
}

#pragma mark - 懒加载
- (UILabel *)tipLabel {
    if (!_tipLabel) {
        UILabel *label = [[UILabel alloc] init];
        label.backgroundColor = [UIColor blackColor];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:13];
        label.text = @"下拉可以加载更多哦!";
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 5;
        label.layer.masksToBounds = YES;
        label.alpha = 0.0;
        label.w = KLTipLabelW;
        label.h = KLTipLabelH;
        label.x = (KLScreenWidth - label.w) * 0.5;
        label.y = (KLScreenHeight - label.h) * 0.5;
        [[UIApplication sharedApplication].keyWindow addSubview:label];
        _tipLabel = label;
    }
    return _tipLabel;
}

- (UILabel *)feedBack {
    if (!_feedBack) {
        UILabel *label = [[UILabel alloc] init];
        label.backgroundColor = [UIColor blackColor];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:13];
        label.text = @"感谢您宝贵的意见,我们会再接再厉!!";
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 5;
        label.layer.masksToBounds = YES;
        label.alpha = 0.0;
        label.w = KLFeedBackLabelW;
        label.h = KLFeedBackLabelH;
        label.x = (KLScreenWidth - label.w) * 0.5;
        label.y = (KLScreenHeight - label.h) * 0.5;
        [[UIApplication sharedApplication].keyWindow addSubview:label];
        _feedBack = label;
    }
    return _feedBack;
}

@end
